import yaml
from models import ConnectInfo

class ConfigLoader:
    def __init__(self, file_path: str):
        self.configFile = file_path
        self.config: dict[str, dict] | None = None
        self.servers: dict[str, ConnectInfo] = {}
        self._load()

    def _load(self):
        try:
            with open(self.configFile, 'r') as file:
                config = yaml.safe_load(file)
                self._struct_check(config)
                for info in config['ssh']:
                    connInfo = ConnectInfo(
                        name=info.get('name', ''),
                        hostname=info.get('host', ''),
                        port=info.get('port', ''),
                        username=info.get('user', ''),
                        pwd=info.get('pwd', ''),
                        cert_file=info.get('key_file', None),
                        group=info.get('group', '')
                    )
                    self.servers[connInfo.name] = connInfo
        except Exception as e:
            print(f"✗ fail to load config: {e}")
    
    def get_connectInfo(self, name: str | None = None):
        if name:
            return self.servers.get(name)
        return self.servers
    
    def _struct_check(self, config):
        if 'version' not in config or 'ssh' not in config:
            raise ValueError("version or ssh not in yaml.config, please check it")
        servers = config["ssh"]
        print(f"have loaded {len(servers)} servers")